var stompClient = null;
var wsCreateHandler = null;
var _index = 0;
function connect(selfId) {
	var userId = selfId?selfId: GetQueryString("userId")
	var host = window.location.host; // 带有端口号
	var socket = new SockJS("http://" + host + "/websocket");
	stompClient = Stomp.over(socket);
	stompClient.connect({}, function (frame) {
		console.log(frame)
		debugger;
		writeToScreen("connected: " + frame);
		stompClient.subscribe('/topic/test', function (response) {
			console.log('/topic response', response)
			writeToScreen(response);
		});
		stompClient.subscribe('/topic/chat/'+userId, function (response) {
			console.log('/topic/chat/'+userId+' response', response)
			// _index++
			// console.log(_index)
			// if(_index%2 === 0){
			// 	console.log(response.a.b.c)
			// }
			writeToScreen(response);
			response.ack()
		},{ack: 'client'});

		}, function (error) {
			console.log('连接中断:', error)
			// wsCreateHandler && clearTimeout(wsCreateHandler);
			// wsCreateHandler = setTimeout(function () {
			// 	console.log("重连...");
			// 	connect();
			// 	console.log("重连完成");
			// }, 1000);
		}
	)
}

function disconnect() {
	if (stompClient != null) {
		stompClient.disconnect();
	}
	writeToScreen("disconnected");
}

function writeToScreen(message) {
	if(DEBUG_FLAG){
		$("#debuggerInfo").val($("#debuggerInfo").val() + "\n" + message);
	}
}

function GetQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
	var context = "";
	if (r != null)
		context = r[2];
	reg = null;
	r = null;
	return context == null || context == "" || context == "undefined" ? "" : context;
}
